<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRole } from "./utils/hook";
import {
  getResourcesList,
  getRolesResources,
  updateRolesResources
} from "@/api/rsapi";
import { closeAllDialog } from "@/components/ReDialog";
import { message } from "@/utils/message";

const { columnsResource } = useRole();
const roleOptions = ref([]);
const resourcetableRef = ref();

export interface FormProps {
  tempid: {
    id: number;
  };
}
const props = withDefaults(defineProps<FormProps>(), {
  tempid: () => ({ id: 0 })
});
const newId = ref(props.tempid);

// 获取用户角色  关联信息选择
const getUserRoles = () => {
  getRolesResources({ id: newId.value.id }).then(res => {
    let list = res;
    let bits;
    const { toggleRowSelection } = resourcetableRef.value.getTableRef();

    roleOptions.value.forEach((item: any) => {
      // 初始化
      item.get = false;
      item.post = false;
      item.put = false;
      item.delete = false;
      item.selection = false;

      (list as any).forEach((v: any) => {
        if (item.id === v.resource.id) {
          bits = numTo4Bits(v.method);
          item.get = Boolean(bits[0]);
          item.post = Boolean(bits[1]);
          item.put = Boolean(bits[2]);
          item.delete = Boolean(bits[3]);
          item.selection = true;
          toggleRowSelection(item, true);
        }
      });
    });
  });
};

// 所有资源列表
const getOptionsRes = async () => {
  let tempValue = (await getResourcesList({ page: 1, size: 1000 })).elements;
  roleOptions.value = tempValue;
  getUserRoles();
};

// 比特位转换
/**
 * num.toString(2)：将数值转换为二进制字符串。
 * .padStart(4, '0')：在字符串前面填充0，直到长度为4。
 * [...]：将字符串转换为字符数组。
 * .map(Number)：将字符数组转换为数字数组。
 */
function numTo4Bits(num) {
  return [...num.toString(2).padStart(4, "0")].map(Number);
}

function bitsToNum(bits) {
  return parseInt(bits.join(""), 2);
}

// 确定按钮
const onSure = () => {
  let resourceMappings = [];
  seleArr.forEach((item: any) => {
    resourceMappings.push({
      id: item.id,
      method: bitsToNum([
        Number(item.get),
        Number(item.post),
        Number(item.put),
        Number(item.delete)
      ])
    });
  });
  updateRolesResources({ id: newId.value.id, resourceMappings }).then(res => {
    if (res.id) {
      message("关联信息修改成功", { type: "success" });
      setTimeout(() => {
        closeAllDialog();
      }, 300);
    }
  });
};

// 多选 关联信息选择
let seleArr = [];
const handleSelectionChange = val => {
  console.log("handleSelectionChange", val);
  seleArr = val;
};

// const handleCellClick = (row, column, cell, event) => {
//   console.log("handleCellClick", row, column, cell, event);
// };

getOptionsRes();

onMounted(() => {
  // getOptionsRes();
});
</script>

<template>
  <div class="tablemain">
    <pure-table
      ref="resourcetableRef"
      align-whole="center"
      showOverflowTooltip
      table-layout="auto"
      :data="roleOptions"
      :columns="columnsResource"
      :header-cell-style="{
        background: 'var(--el-fill-color-light)',
        color: 'var(--el-text-color-primary)'
      }"
      class="pb-5"
      @selection-change="handleSelectionChange"
    />
    <el-button
      class="absolute bottom-[16px] right-[16px] w-[60px]"
      type="primary"
      text
      bg
      @click="onSure"
    >
      确定
    </el-button>
  </div>
</template>
